package com.tanhua.server.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tanhua.dubbo.server.api.UserLikeApi;
import com.tanhua.dubbo.server.api.UserLocationApi;
import com.tanhua.dubbo.server.pojo.RecommendUser;
import com.tanhua.dubbo.server.vo.PageInfo;
import com.tanhua.dubbo.server.vo.UserLocationVo;
import com.tanhua.server.enums.SexEnum;

import com.tanhua.server.pojo.Question;
import com.tanhua.server.pojo.User;
import com.tanhua.server.pojo.UserInfo;
import com.tanhua.server.utils.UserThreadLocal;
import com.tanhua.server.vo.NearUserVo;
import com.tanhua.server.vo.PageResult;
import com.tanhua.server.vo.RecommendUserQueryParam;
import com.tanhua.server.vo.TodayBest;
import org.springframework.util.CollectionUtils;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.*;

/**
 * @Author: JinboYang
 * @Description:
 * @Date: Created in 19:11 2021/1/4
 * @ModifiedBy:
 */
@Service
public class TodayBestService {
    @Autowired
    private UserService userService;

    @Autowired
    private RecommendUserService recommendUserService;

    @Autowired
    private UserInfoService userInfoService;

    @Value("${tanhua.sso.default.user}")
    private Long defaultUser;

    @Value("${tanhua.sso.default.recommend.users}")
    private String defaultRecommendUsers;

    @Value("${tanhua.sso.url}")
    private String url;

    @Autowired
    private RestTemplate restTemplate;

    @Reference(version = "1.0.0")
    private UserLocationApi userLocationApi;

    @Reference(version = "1.0.0")
    private UserLikeApi userLikeApi;

    @Autowired
    private QuestionService questionService;

    @Autowired
    private IMService imService;

    private static final ObjectMapper MAPPER = new ObjectMapper();

    /**
     * @Description: 根据传过来的token找到今日佳人
     * @Param:[token]
     * @return:com.tanhua.server.vo.TodayBest
     * @Author:JinboYang
     * @Date:2021/1/4
     */
    public TodayBest queryTodayBest(String token) {
        //校验token是否有效,通过sso的接口进行校验
        User user = userService.queryUserByToken(token);
        //说明token已经失效,返回null
        if (null == user) {
            return null;
        }
        //查询推荐用户
        TodayBest todayBest = recommendUserService.queryTodayBest(user.getId());
        if (null == todayBest) {
            //给出默认的推荐用户 在配置文件中有设置默认用户直接注入
            todayBest = recommendUserService.queryTodayBest(defaultUser);
            todayBest.setId(defaultUser);
            todayBest.setFateValue(90L);
        }
        //补全个人信息
        UserInfo userInfo = this.userInfoService.queryUserInfoByUserId(todayBest.getId());
        //如果为空直接返回null
        if (null == userInfo) {
            return null;
        }
        //补全个人信息
        todayBest.setAvatar(userInfo.getLogo());
        todayBest.setAge(userInfo.getAge());
        todayBest.setNickname(userInfo.getNickName());
        todayBest.setGender(userInfo.getSex().getValue() == 1 ? "man" : "woman");
        todayBest.setTags(StringUtils.split(userInfo.getTags(), ","));

        return todayBest;
    }

    public PageResult queryRecommendation(String token, RecommendUserQueryParam param) {
        //获得用户对象
        User user = userService.queryUserByToken(token);
        if (null == user) {
            return null;
        }

        PageResult pageResult = new PageResult();
        pageResult.setPage(param.getPage());
        pageResult.setPagesize(param.getPagesize());

        PageInfo<RecommendUser> pageInfo = this.recommendUserService.queryRecommendUserList(user.getId(), param.getPage(), param.getPagesize());
        List<RecommendUser> records = pageInfo.getRecords();
        //判断集合中是否有数据
        if (CollectionUtils.isEmpty(records)) {
            //进行切割
            String[] userIdsStr = StringUtils.split(defaultRecommendUsers, ",");
            for (String s : userIdsStr) {
                RecommendUser recommendUser = new RecommendUser();
                recommendUser.setUserId(Long.valueOf(s));
                recommendUser.setId(ObjectId.get());
                recommendUser.setScore(RandomUtils.nextDouble(70d, 90d));
                records.add(recommendUser);
            }
        }

        //收集推荐用户的id
        Set<Long> userIds = new HashSet<>();
        for (RecommendUser record : records) {
            userIds.add(record.getUserId());
        }
        QueryWrapper queryWrapper = new QueryWrapper();
        //用户的id参数
        queryWrapper.in("user_id", userIds);

        /*//查询城市参数
        if (StringUtils.isNotEmpty(param.getCity())) {
            queryWrapper.like("city", param.getCity());
        }

        //查询性别参数
        if (StringUtils.isNotEmpty(param.getGender())) {
            queryWrapper.eq("sex", StringUtils.equals(param.getGender(), "man") ? 1 : 2);
        }

        //查询年龄参数
        if (param.getAge() != null) {
            queryWrapper.le("age", param.getAge());
        }*/

        //
        List<UserInfo> userInfoList = this.userInfoService.queryUserInfoList(queryWrapper);
        if (CollectionUtils.isEmpty(userInfoList)) {
            //没有查到用户基本信息
            return pageResult;
        }

        List<TodayBest> todayBests = new ArrayList<>();
        for (UserInfo userInfo : userInfoList) {
            TodayBest todayBest = new TodayBest();
            //补全个人信息
            todayBest.setId(userInfo.getUserId());
            todayBest.setAvatar(userInfo.getLogo());
            todayBest.setAge(userInfo.getAge());
            todayBest.setNickname(userInfo.getNickName());
            todayBest.setGender(userInfo.getSex().getValue() == 1 ? "man" : "woman");
            todayBest.setTags(StringUtils.split(userInfo.getTags(), ","));

            //设置缘分值
            for (RecommendUser record : records) {
                if (record.getUserId().longValue() == userInfo.getUserId().longValue()) {
                    double score = Math.floor(record.getScore());
                    todayBest.setFateValue(Double.valueOf(score).longValue());
                    break;
                }
            }
            todayBests.add(todayBest);
        }
        //缘分值倒序排列
        Collections.sort(todayBests, (o1, o2) -> new Long(o2.getFateValue() - o1.getFateValue()).intValue());
        pageResult.setItems(todayBests);
        return pageResult;
    }

    /**
     * @Description: 查看今日佳人详情
     * @Param:[userId]
     * @return:com.tanhua.server.vo.TodayBest
     * @Author:JinboYang
     * @Date:2021/1/13
     */
    public TodayBest queryTodayBest(Long userId) {
        User user = UserThreadLocal.get();
        TodayBest todayBest = new TodayBest();
        //补全信息
        UserInfo userInfo = this.userInfoService.queryUserInfoByUserId(userId);
        todayBest.setAvatar(userInfo.getLogo());
        todayBest.setId(userId);
        todayBest.setNickname(userInfo.getNickName());
        todayBest.setGender(userInfo.getSex().name().toLowerCase(Locale.ROOT));
        todayBest.setTags(StringUtils.split(userInfo.getTags(), ","));
        todayBest.setAge(userInfo.getAge());

        double score = this.recommendUserService.queryScore(userId, user.getId());
        if (score == 0) {
            //默认值
            score = 98;
        }

        return todayBest;
    }

    /**
     * @Description: 查询陌生人问题
     * @Param:[userId]
     * @return:java.lang.String
     * @Author:JinboYang
     * @Date:2021/1/13
     */
    public String queryQuestion(Long userId) {
        Question question = this.questionService.queryQuestion(userId);
        if (question != null) {
            return question.getTxt();
        }
        return "";
    }

    /**
     * @Description: 回答陌生人问题
     * @Param:[userId, reply]
     * @return:java.lang.Boolean
     * @Author:JinboYang
     * @Date:2021/1/13
     */
    public Boolean replyQuestion(Long userId, String reply) {
        User user = UserThreadLocal.get();
        UserInfo userInfo = this.userInfoService.queryUserInfoByUserId(user.getId());
        //构建消息内容
        Map<String, Object> msg = new HashMap<>();
        msg.put("usrId", user.getId().toString());
        msg.put("nickname", this.queryQuestion(userId));
        msg.put("strangerQuestion", userInfo.getNickName());
        msg.put("reply", reply);
        try {
            String msgStr = MAPPER.writeValueAsString(msg);
            String targetUrl = this.url + "/user/huanxin/messages";

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

            MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
            params.add("target", userId.toString());
            params.add("msg", msgStr);

            HttpEntity<MultiValueMap<String, String>> httpEntity = new HttpEntity<>(params, headers);
            ResponseEntity<Void> responseEntity = this.restTemplate.postForEntity(targetUrl, httpEntity, Void.class);

            return responseEntity.getStatusCodeValue() == 200;

        } catch (Exception e) {
            e.printStackTrace();
        }

        return false;
    }

    /**
     * @Description: 搜附近
     * @Param:[gender, distance]
     * @return:java.util.List<com.tanhua.server.vo.NearUserVo>
     * @Author:JinboYang
     * @Date:2021/1/14
     */
    public List<NearUserVo> queryNearUser(String gender, String distance) {
        User user = UserThreadLocal.get();
        //查询当前用户位置
        UserLocationVo userLocationVo = this.userLocationApi.queryByUserId(user.getId());
        Double longitude = userLocationVo.getLongitude();
        Double latitude = userLocationVo.getLatitude();

        //根据当前信息搜索附近好友
        List<UserLocationVo> userLocationVoList = this.userLocationApi.queryUserFromLocation(longitude, latitude, Integer.valueOf(distance));
        if (CollectionUtils.isEmpty(userLocationVoList)) {
            return Collections.emptyList();
        }

        //获取附近的id
        List<Long> userIds = new ArrayList<>();
        for (UserLocationVo locationVo : userLocationVoList) {
            userIds.add(locationVo.getUserId());
        }

        //查询
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("user_id", userIds);
        //查询性别
        if (StringUtils.equalsIgnoreCase(gender, "man")) {
            queryWrapper.eq("sex", SexEnum.MAN);
        } else {
            queryWrapper.eq("sex", SexEnum.WOMAN);
        }

        List<UserInfo> userInfoList = this.userInfoService.queryUserInfoList(queryWrapper);
        List<NearUserVo> nearUserVoList = new ArrayList<>();
        for (UserLocationVo locationVo : userLocationVoList) {
            //排除自己
            if (locationVo.getUserId().longValue() == user.getId().longValue()) {
                continue;
            }

            for (UserInfo userInfo : userInfoList) {
                if (locationVo.getUserId().longValue() == userInfo.getUserId().longValue()) {
                    NearUserVo nearUserVo = new NearUserVo();
                    nearUserVo.setUserId(userInfo.getUserId());
                    nearUserVo.setAvatar(userInfo.getLogo());
                    nearUserVo.setNickname(userInfo.getNickName());
                    nearUserVoList.add(nearUserVo);
                    break;
                }
            }
        }
        return nearUserVoList;
    }

    /**
     * @Description: 卡片列表
     * @Param:[]
     * @return:java.util.List<com.tanhua.server.vo.TodayBest>
     * @Author:JinboYang
     * @Date:2021/1/14
     */
    public List<TodayBest> queryCardsList() {
        User user = UserThreadLocal.get();
        PageInfo<RecommendUser> pageInfo = this.recommendUserService.queryRecommendUserList(user.getId(), 1, 50);
        if (CollectionUtils.isEmpty(pageInfo.getRecords())) {
            //如果查询为空则使用默认的推荐
            String[] split = StringUtils.split(defaultRecommendUsers, ",");
            for (String s : split) {
                RecommendUser recommendUser = new RecommendUser();
                recommendUser.setUserId(Long.valueOf(s));
                recommendUser.setToUserId(user.getId());
                pageInfo.getRecords().add(recommendUser);
            }
        }

        List<RecommendUser> records = pageInfo.getRecords();
        int showCount = Math.min(10, records.size());
        //打散集合
        Collections.shuffle(records);

        List<RecommendUser> newRecommendUserList = records.subList(0, showCount);

        //创建所有的ids集合
        List<Long> userIds = new ArrayList<>();

        for (RecommendUser recommendUser : newRecommendUserList) {
            userIds.add(recommendUser.getUserId());
        }

        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("user_id", userIds);
        List<UserInfo> userInfoList = this.userInfoService.queryUserInfoList(queryWrapper);
        List<TodayBest> todayBestList = new ArrayList<>();
        for (UserInfo userInfo : userInfoList) {
            TodayBest todayBest = new TodayBest();
            todayBest.setId(userInfo.getUserId());
            todayBest.setAge(userInfo.getAge());
            todayBest.setAvatar(userInfo.getLogo());
            todayBest.setGender(userInfo.getSex().name().toLowerCase());
            todayBest.setNickname(userInfo.getNickName());
            todayBest.setTags(StringUtils.split(userInfo.getTags(), ','));
            todayBest.setFateValue(0L);

            todayBestList.add(todayBest);
        }
        return todayBestList;
    }

    /**
     * @Description: 喜欢
     * @Param:[likeUserId]
     * @return:void
     * @Author:JinboYang
     * @Date:2021/1/14
     */
    public Boolean likeUser(Long likeUserId) {
        User user = UserThreadLocal.get();
        String id = this.userLikeApi.saveUserLike(user.getId(), likeUserId);
        //判断id是否为空
        if (StringUtils.isEmpty(id)) {
            return false;
        }
        if (this.userLikeApi.isMutualLike(user.getId(), likeUserId)) {
            //相互喜欢成为好友
            this.imService.contactUser(likeUserId);
        }

        return true;

    }

    /**
       * @Description: 不喜欢
       * @Param:[likeUserId]
       * @return:java.lang.Boolean
       * @Author:JinboYang
       * @Date:2021/1/14
       */
    public Boolean disLikeUser(Long likeUserId) {
        User user = UserThreadLocal.get();
        return this.userLikeApi.deleteUserLike(user.getId(),likeUserId);
    }
}
